package com.yegrina.twt.controller;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.yegrina.twt.domain.SubmitReportCommand;
import com.yegrina.twt.validator.SubmitReportValidator;



@Controller
@RequestMapping("/report/submitReport.do")
public class SubmitReportController {

	@RequestMapping(method=RequestMethod.GET)
	public String form(){
		return "report/submitReportForm";
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public String submit(@ModelAttribute("report")SubmitReportCommand command, BindingResult errors){
		
		new SubmitReportValidator().validate(command, errors);

		if(errors.hasErrors()){
			return form();
		}
		
		if(!command.getReportFile().isEmpty()){
			String path = "D:/javaWork/workspace-spring/yegrina/WebContent/userImage";
		
			try{
				
				byte fileData[] = command.getReportFile().getBytes();
				
				FileOutputStream fos = new FileOutputStream(path + "/" + command.getReportFile().getOriginalFilename());
				fos.write(fileData);
				fos.close();
				
			}catch(FileNotFoundException e){
				e.printStackTrace();
			}catch (IOException e) {
				e.printStackTrace();
			}
			
			//아리와 같이 파일 업로드 처리도지원
			/*
			try{
			File file = new File(path + "/" + command.getReportFile().getOriginalFilename());
			command.getReportFile().transferTo(file);
			
			}catch(IllegalStateException e){
				e.printStackTrace();
			}catch (IOException e) {
				e.printStackTrace();
			}*/
			System.out.println("주제 : " + command.getSubject());
			System.out.println("업로드한 파일 : "+ command.getReportFile().getOriginalFilename());
			System.out.println("소스 코드 크키 : " + command.getReportFile().getSize());
			
		}
	
		return "report/submittedReport";
	}
	
}
